<?php

namespace app\api\model;

use app\admin\model\vip\Code;
use app\exceptions\ApiException;
use think\Db;
use think\Model;

/**
 * Banner
 */
class VipCard extends Model
{
    // 表名
    protected $name = 'vip_card';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = true;

    protected $expire_type = [1 => '1天', 2 => '6个月', 3 => "1年"];


    public function getVipCardSearch($params)
    {
        $vip_type = $params['vip_type'] ?? 1;
        $list = self::where(['type' => $vip_type])->field('id,name')->select();
        return api_message($list);
    }


    public function getImageAttr($value)
    {
        return full_url($value);
    }


    public function getVipCard()
    {
        // 获取所有有效的VIP卡信息
        $list = self::where(['status' => 1])
            ->field('id, image, name, type, use_type, expire_type, nums, price, book_notice')
            ->order('weigh DESC')
            ->select()
            ->toArray();

        // 遍历处理每个VIP卡的信息
        foreach ($list as &$val) {
            $val['nums'] = ($val['use_type'] == 2) ? "无限次数" : $val['nums'] . "次";
            $val['expire_type'] = $this->expire_type[$val['expire_type']] ?? '未知'; // 默认“未知”防止异常
            //查询该会员卡支持的总数
            $val['scenic_nums'] = $this->getInterestsByVipCardIdNums($val['id'], $val['type']);
            $val['interests'] = $this->getInterestsByVipCardId($val['id'], $val['type']);
            unset($val['use_type']);
        }

        // 返回最终数据
        return api_message($list);
    }


    public function getInterestsByVipCardIdNums($vip_card_id, $vip_type){
        $map = [];
        if ($vip_type == 1) {
            $map[] = ['vip_card_ids', 'like', '%' . $vip_card_id . "%"];
            $map[] = ['status', '=', 1];
            //查询景区
            $nums = (new Scenic())->where($map)->count();

        } else {
            $map[] = ['status', '=', 1];
            $map[] = ['vip_card_ids', 'like', '%' . $vip_card_id . "%"];
            $nums = Hotel::where($map)->count();
        }

        return $nums;
    }


    public function getInterestsByVipCardId($vip_card_id, $vip_type)
    {
        $map = [];
        if ($vip_type == 1) {
            $map[] = ['s.vip_card_ids', 'like', '%' . $vip_card_id . "%"];
            $map[] = ['s.status', '=', 1];
            //查询景区
            $list = (new Scenic())->alias('s')
                ->join('cate c', 'c.id = s.cate_id')
                ->where($map)
                ->field('s.name,s.cover,c.name as cate_name,s.address,s.scenic_des,s.vip_card_ids')
                ->limit(5)->select();
        } else {
            $map[] = ['status', '=', 1];
            $map[] = ['vip_card_ids', 'like', '%' . $vip_card_id . "%"];
            $list = Hotel::where($map)
                ->field('id as hotel_id,name,cover,address,hotel_cate_ids,vip_card_ids')
                ->limit(5)->select();
        }

        foreach ($list as &$val){
            $val['cover'] = $val['cover'] ? full_url($val['cover']) : '';
        }
        return $list;
    }



    public function getNoActivation($params){
        $member_id = $params['member_id'] ?? '';
        $member_vip_card = (new MemberVipCard())->where(['member_id' => $member_id,'status'=> 0])->find();
        if(!$member_vip_card) return api_message();
        //查询激活码
        $vip_code = (new Code())->where(['number' => $member_vip_card['vip_code']])->find();
        if(!$vip_code) return api_message();
        $data = [
            'code' =>$vip_code['number'],
            'password' => $vip_code['password'],
        ];
        return api_message($data);
    }


    public function toActivation($params){
        $member_id = $params['member_id'] ?? '';
        $code = $params['code'] ?? '';
        $password = $params['password'] ?? '';
        $city = $params['city'] ?? '';

        //判断是否已经认证
        $member = (new Member())->where(['id' => $member_id])->find();
        if(!$member['username'] || !$member['id_number']) throw new ApiException('请先实名认证');

       //查询卡密信息
        $map['number'] = $code;
        $map['password'] = $password;
        $vip_code = (new Code())->where($map)->find();
        if(!$vip_code) throw new ApiException('卡密错误');
        if($vip_code['status'] == 1 || $vip_code['status'] ==2) throw new ApiException('该卡密已使用或者已过期');
        if($vip_code['is_freeze'] == 1) throw new ApiException('该卡不存在，请联系管理员');

        $vip_card = (new VipCard())->where(['id' => $vip_code['vip_card_id']])->find();
        if(!$vip_card) throw new ApiException('会员已下架，请联系管理员');


        $member_tiyan_vip = (new MemberVipCard())->where(['member_id' => $member_id,'status'=>[1,2],'vip_card_id'=>[1,2]])->count();
        if($member_tiyan_vip && in_array($vip_card['id'],[1,2])) throw new ApiException('体验卡每个账号只能使用一次');

        //查询该类型会员卡是否已经在使用
        $member_type_vip = (new MemberVipCard())->where(['member_id' => $member_id,'vip_type' => $vip_card['type'],'status'=>1])->find();
        if($member_type_vip) throw new ApiException('该会员类型已存在，请联系管理员绑定新卡');

        try {
            \think\facade\Db::startTrans();
            if($vip_card['use_type'] == 1) $data['nums'] = $vip_card['nums'];
            $start = date('Y-m-d H:i:s');
            $data['expire_time'] = $this->getExpireTime($start,$vip_card['expire_type']);
            $data['city'] = $city;
            $data['status'] = 1;
            //查询是否有未激活的该卡
            $member_vip_card = (new MemberVipCard())->where(['member_id' => $member_id,'vip_code' => $code,'status'=>0])->find();
            if($member_vip_card){
                //直接更新该数据
                $data['update_time'] = time();
                (new MemberVipCard())->where(['member_id' => $member_id,'vip_code' => $code])->update($data);
            }else{
                //更新卡密状态
                (new Code())->where(['id' => $vip_code['id']])->update(['status' => 1,'update_time' => time()]);
                //添加会员
                $data['vip_type'] = $vip_card['type'];
                $data['admin_id'] = $vip_code['admin_id'];
                $data['vip_code'] = $code;
                $data['vip_card_id'] = $vip_code['vip_card_id'];
                $data['member_id'] = $member_id;
                (new MemberVipCard())->save($data);
            }
            \think\facade\Db::commit();
            return api_message([],'激活成功');
            //查询是否已经激活其他的卡
        }catch(\Exception $e) {
              \think\facade\Db::rollback();
              throw new ApiException($e->getMessage());
        }

    }


    public function getExpireTime($start,$type)
    {
        switch ($type) {
            case 1:
                $date = date('Y-m-d H:i:s', strtotime($start . '+1 day'));
                break;
            case 2:
                $date = date('Y-m-d H:i:s', strtotime($start . '+6 month'));
                break;
            case 3:
                $date = date('Y-m-d H:i:s', strtotime($start . '+1 year'));
                break;
        }
        return strtotime($date);
    }





    public function getCode($code)
    {
        preg_match('/([a-zA-Z]+)(\d+)/', $code, $matches);
        return array(
            'prefix' => $matches[1],  // 字母部分
            'number' => $matches[2],  // 数字部分
        );
    }

}
